'use client';

import { useState, useEffect, useRef } from 'react';
import styled from 'styled-components';
import * as echarts from 'echarts/core';
import { BarChart } from 'echarts/charts';
import {
  TooltipComponent,
  LegendComponent,
  GridComponent,
  ToolboxComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

// 注册必须的组件
echarts.use([
  BarChart,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  ToolboxComponent,
  CanvasRenderer
]);

// 样式组件
const FlightPlansContainer = styled.div`
  display: flex;
  flex-direction: column;
  height: 100%;
`;

const TabContainer = styled.div`
  display: flex;
  margin-bottom: 10px;
  border-bottom: 1px solid rgba(24, 144, 255, 0.2);
`;

const TabButton = styled.div<{ active: boolean }>`
  padding: 5px 12px;
  font-size: 12px;
  cursor: pointer;
  color: ${props => props.active ? 'white' : '#a0cfff'};
  border-bottom: 2px solid ${props => props.active ? '#1890ff' : 'transparent'};
  transition: all 0.3s;
  position: relative;
  
  &:hover {
    color: white;
  }
  
  &::after {
    content: '';
    position: absolute;
    bottom: -2px;
    left: 0;
    width: ${props => props.active ? '100%' : '0'};
    height: 2px;
    background-color: #1890ff;
    transition: all 0.3s;
  }
`;

const ContentContainer = styled.div`
  flex: 1;
  overflow: hidden;
  position: relative;
`;

const ChartContainer = styled.div`
  width: 100%;
  height: 100%;
`;

const PlansList = styled.div`
  height: 100%;
  overflow-y: auto;
  
  /* 自定义滚动条 */
  &::-webkit-scrollbar {
    width: 4px;
  }
  
  &::-webkit-scrollbar-track {
    background: rgba(0, 0, 0, 0.1);
  }
  
  &::-webkit-scrollbar-thumb {
    background: rgba(24, 144, 255, 0.3);
    border-radius: 2px;
  }
`;

const PlanItem = styled.div<{ status: 'completed' | 'active' | 'pending' | 'delayed' }>`
  display: flex;
  justify-content: space-between;
  padding: 8px;
  margin-bottom: 4px;
  font-size: 12px;
  background: ${props => {
    switch (props.status) {
      case 'completed': return 'rgba(82, 196, 26, 0.1)';
      case 'active': return 'rgba(24, 144, 255, 0.1)';
      case 'pending': return 'rgba(250, 173, 20, 0.1)';
      case 'delayed': return 'rgba(255, 77, 79, 0.1)';
      default: return 'transparent';
    }
  }};
  border-left: 3px solid ${props => {
    switch (props.status) {
      case 'completed': return '#52c41a';
      case 'active': return '#1890ff';
      case 'pending': return '#faad14';
      case 'delayed': return '#ff4d4f';
      default: return 'transparent';
    }
  }};
  border-radius: 2px;
`;

const PlanInfo = styled.div`
  display: flex;
  flex-direction: column;
`;

const PlanName = styled.div`
  color: white;
  margin-bottom: 2px;
`;

const PlanTime = styled.div`
  color: #a0cfff;
`;

const PlanStatus = styled.div<{ status: 'completed' | 'active' | 'pending' | 'delayed' }>`
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 10px;
  background: ${props => {
    switch (props.status) {
      case 'completed': return 'rgba(82, 196, 26, 0.2)';
      case 'active': return 'rgba(24, 144, 255, 0.2)';
      case 'pending': return 'rgba(250, 173, 20, 0.2)';
      case 'delayed': return 'rgba(255, 77, 79, 0.2)';
      default: return 'transparent';
    }
  }};
  color: ${props => {
    switch (props.status) {
      case 'completed': return '#52c41a';
      case 'active': return '#1890ff';
      case 'pending': return '#faad14';
      case 'delayed': return '#ff4d4f';
      default: return 'white';
    }
  }};
  align-self: center;
`;

// 飞行计划类型接口定义
interface FlightPlan {
  id: string;
  name: string;
  time: string;
  status: 'completed' | 'active' | 'pending' | 'delayed';
  completionRate?: number;
}

// 模拟飞行计划数据
const mockFlightPlans: FlightPlan[] = [
  { id: 'FP-001', name: '东片区巡逻任务', time: '09:00 - 10:30', status: 'completed', completionRate: 100 },
  { id: 'FP-002', name: '西片区安防巡检', time: '10:30 - 12:00', status: 'active', completionRate: 65 },
  { id: 'FP-003', name: '南片区数据采集', time: '13:00 - 14:30', status: 'pending' },
  { id: 'FP-004', name: '中心区域高空监测', time: '15:00 - 16:30', status: 'pending' },
  { id: 'FP-005', name: '北片区应急演练', time: '16:30 - 18:00', status: 'delayed' },
  { id: 'FP-006', name: '边界区域巡逻', time: '19:00 - 20:30', status: 'pending' }
];

// 获取状态对应文字
const getStatusText = (status: 'completed' | 'active' | 'pending' | 'delayed') => {
  switch (status) {
    case 'completed': return '已完成';
    case 'active': return '执行中';
    case 'pending': return '待执行';
    case 'delayed': return '已延迟';
    default: return '';
  }
};

export default function FlightPlans() {
  const [flightPlans, setFlightPlans] = useState<FlightPlan[]>(mockFlightPlans);
  const [activeTab, setActiveTab] = useState<'chart' | 'list'>('chart');
  const chartRef = useRef<HTMLDivElement>(null);
  const [chartInstance, setChartInstance] = useState<echarts.ECharts | null>(null);

  // 计算状态统计
  const statusStats = {
    completed: flightPlans.filter(plan => plan.status === 'completed').length,
    active: flightPlans.filter(plan => plan.status === 'active').length,
    pending: flightPlans.filter(plan => plan.status === 'pending').length,
    delayed: flightPlans.filter(plan => plan.status === 'delayed').length
  };

  // 初始化图表
  useEffect(() => {
    if (!chartRef.current) return;
    
    // 如果已有实例，先销毁
    if (chartInstance) {
      chartInstance.dispose();
    }
    
    const instance = echarts.init(chartRef.current);
    setChartInstance(instance);
    
    // 监听窗口大小变化
    const resizeHandler = () => {
      if (instance) {
        instance.resize();
      }
    };
    
    window.addEventListener('resize', resizeHandler);
    
    return () => {
      window.removeEventListener('resize', resizeHandler);
      instance.dispose();
    };
  }, [activeTab]); // 添加activeTab作为依赖项，确保tab切换时重新初始化图表

  // 更新图表数据
  useEffect(() => {
    if (!chartInstance) return;
    
    // 图表配置
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['已完成', '执行中', '待执行', '已延迟'],
        axisLine: {
          lineStyle: {
            color: '#a0cfff'
          }
        },
        axisLabel: {
          color: '#a0cfff',
          fontSize: 10
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          show: false
        },
        axisLabel: {
          color: '#a0cfff',
          fontSize: 10
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(160, 207, 255, 0.1)'
          }
        }
      },
      series: [
        {
          name: '飞行计划数量',
          type: 'bar',
          data: [
            {
              value: statusStats.completed,
              itemStyle: { 
                color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                  { offset: 0, color: '#52c41a' },
                  { offset: 1, color: '#7be141' }
                ])
              }
            },
            {
              value: statusStats.active,
              itemStyle: { 
                color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                  { offset: 0, color: '#1890ff' },
                  { offset: 1, color: '#69c0ff' }
                ])
              }
            },
            {
              value: statusStats.pending,
              itemStyle: { 
                color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                  { offset: 0, color: '#faad14' },
                  { offset: 1, color: '#ffc53d' }
                ])
              }
            },
            {
              value: statusStats.delayed,
              itemStyle: { 
                color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                  { offset: 0, color: '#f5222d' },
                  { offset: 1, color: '#ff7875' }
                ])
              }
            }
          ],
          barWidth: '40%',
          label: {
            show: true,
            position: 'top',
            color: 'white',
            fontSize: 10
          },
          itemStyle: {
            borderRadius: 4
          }
        }
      ]
    };
    
    // 设置图表
    chartInstance.setOption(option);
  }, [chartInstance, statusStats]);
  
  // 模拟数据更新
  useEffect(() => {
    const updateTimer = setInterval(() => {
      // 随机更新一个飞行计划状态
      const randomIndex = Math.floor(Math.random() * flightPlans.length);
      const updatedPlans = [...flightPlans];
      const plan = { ...updatedPlans[randomIndex] };
      
      // 模拟状态变化逻辑
      if (plan.status === 'active' && (plan.completionRate || 0) < 100) {
        plan.completionRate = (plan.completionRate || 0) + 5;
        if (plan.completionRate >= 100) {
          plan.status = 'completed';
          plan.completionRate = 100;
        }
      } else if (plan.status === 'pending' && Math.random() > 0.7) {
        plan.status = 'active';
        plan.completionRate = 0;
      } else if (plan.status === 'delayed' && Math.random() > 0.8) {
        plan.status = 'active';
        plan.completionRate = 0;
      }
      
      updatedPlans[randomIndex] = plan;
      setFlightPlans(updatedPlans);
    }, 5000);
    
    return () => {
      clearInterval(updateTimer);
    };
  }, [flightPlans]);

  return (
    <FlightPlansContainer>
      <TabContainer>
        <TabButton 
          active={activeTab === 'chart'} 
          onClick={() => setActiveTab('chart')}
        >
          状态统计
        </TabButton>
        <TabButton 
          active={activeTab === 'list'} 
          onClick={() => setActiveTab('list')}
        >
          飞行计划
        </TabButton>
      </TabContainer>
      
      <ContentContainer>
        {activeTab === 'chart' && (
          <ChartContainer ref={chartRef} />
        )}
        
        {activeTab === 'list' && (
          <PlansList>
            {flightPlans.map(plan => (
              <PlanItem key={plan.id} status={plan.status}>
                <PlanInfo>
                  <PlanName>{plan.name}</PlanName>
                  <PlanTime>{plan.time}</PlanTime>
                </PlanInfo>
                <PlanStatus status={plan.status}>
                  {getStatusText(plan.status)}
                  {plan.completionRate !== undefined && plan.status === 'active' ? 
                    ` (${plan.completionRate}%)` : ''}
                </PlanStatus>
              </PlanItem>
            ))}
          </PlansList>
        )}
      </ContentContainer>
    </FlightPlansContainer>
  );
} 